package com.itheima.health.util;

import com.itheima.health.common.MessageConst;
import com.itheima.health.constant.RedisConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Iterator;
import java.util.Set;

@Component //  定义任务实现类
public class QiniuOssScanClean {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    QiniuUtils qiniuUtils;

    @Scheduled(cron = "0 0 3 * * SUN") //  5秒 直接在方法上使用注解即可完成扫描
    public void run() {
        System.out.println("清理redis套餐图片");
        SetOperations setOperations = this.redisTemplate.opsForSet();

//        Set setmealPicList = setOperations.members(RedisConstant.SETMEAL_PIC_List);
        Set setmealPicResources = setOperations.members(RedisConstant.SETMEAL_PIC_RESOURCES);
        Set setmealPicDbResources = setOperations.members(RedisConstant.SETMEAL_PIC_DB_RESOURCES);
        Set difference = setOperations.difference(RedisConstant.SETMEAL_PIC_RESOURCES, RedisConstant.SETMEAL_PIC_DB_RESOURCES);

//        Iterator it = setmealPicList.iterator();
        Iterator it = difference.iterator();
        while (it.hasNext()) {
            String setmealPic = (String) it.next();

            String file = setmealPic.substring(0,setmealPic.indexOf("."));
            Date fileDate = IdWorker.inverseDate(Long.valueOf(file));
            long fileTime = fileDate.getTime();
            long nowTime = System.currentTimeMillis();
            long bjTime = nowTime - (60*60*1000);

            if (bjTime < fileTime) {
                continue;
            }

            qiniuUtils.deleteFileFromQiniu((String) setmealPic);
            setmealPicResources.remove(setmealPic);
        }
    }

}